var fs = require('fs');

let components = {};
let PATH = '.';

readDir(PATH);

function readDir(PATH)  {
    const files = fs.readdirSync(PATH);
    files.forEach(function (item, index) {
        let itemPath = PATH+"/"+item
        let stat = fs.lstatSync(itemPath);

        if (stat.isFile() === true && item.indexOf(".vue")!= -1) {
            let data = fs.readFileSync(itemPath);
            let LFS = {};
            let content = data.toString();
            LFS.template = parse2Template(content);
            LFS.obj = parse2Obj(content);
            components[itemPath] = LFS;
        }else if(stat.isDirectory()){
            readDir(itemPath);
        }
    });
}


/**
 * 将组件转换为TFS对象
 * @param content
 */
function parse2Template(content) {
    //第一步 识别template标签 参考vue
    const templateStartTag = new RegExp(`<template>`);
    const start = content.match(templateStartTag)
    const templateEndTag = new RegExp(`<\/template>`)
    const end = content.match(templateEndTag);
    if(start&&end){
        let template = content.substring(start['index']+10,end["index"]);
        return template;
    }
    return null;
}

function parse2Obj(content) {
    //第一步 识别template标签 参考vue
    const templateStartTag = new RegExp(`<script>`);
    const start = content.match(templateStartTag);
    const templateEndTag = new RegExp(`<\/script>`);
    const end = content.match(templateEndTag);

    if(start&&end){
        let script = content.substring(start['index']+9,end["index"]);
        return script;
    }
    return null;
}

let str = JSON.stringify(components);
str="var Components = " + str;
fs.exists("./dist",function (exists) {
    if(exists){
        fs.writeFile('./dist/component.js',str,function(err,res){
            if (err) {res.status(500).send('Server is error...')}
        })
    }else{
        fs.mkdirSync('dist');
        fs.writeFile('./dist/component.js',str,function(err,res){
            if (err) {res.status(500).send('Server is error...')}
        })
    }

})
;

